(function ( window, undefined ) {
  
  "use strict";

  var GH = function () {};
  
  GH.prototype.$ = function( selector ) {
    var isId = new RegExp( /^#\w+$/ ).test( selector );
    return isId ? document.getElementById ( selector.replace( /^#/g, "" ) ) : document.querySelector ( selector );
  };
  
  GH.prototype.$$ = function( selector ) {
    return document.querySelectorAll ( selector );
  };
  
  GH.prototype.load = function ( type, id, url, callback ) {
    var obj = document.getElementById( id );
    try {
      obj.parentNode.removeChild( obj )
    } catch (e) {

    }

    var insertEle = null;
    if( !type || type == "js" ) {
      insertEle = document.createElement("script");
      insertEle.setAttribute("type", "text/javascript");
      insertEle.setAttribute("src", url);
    } else if ( type == "css" ) {
      insertEle = document.createElement("link");
      insertEle.setAttribute("rel", "stylesheet");
      insertEle.setAttribute("href", url);
    }
    
    insertEle.setAttribute("id", id);
    insertEle.setAttribute("charset", "utf-8");
    
    document.getElementsByTagName("head")[0].appendChild( insertEle );
    insertEle.onload = function() {
      callback && callback();
    }
  };

  GH.prototype.css = function ( obj, attr, value ) {
    switch( arguments.length ) {
      case 2: 
        if ( typeof arguments[1] === "string" ) {
          return getComputedStyle ( obj, false ) [ attr ]; //1
        } else {
          for ( var i in arguments[1] ) { obj.style[i] = attr[i]; } //3
        }
        break;
      case 3:
        obj.style[attr] = value; //2
        break;
      default:
        console.log( "参数传入错误" );
        break;
      };
  };


  GH.prototype.showMessage = function ( message ) {
    var self = this;
    var container = document.createElement( "div" );
    var inner = document.createElement( "span" );
    inner.innerHTML = message;
    this.css(container, {
      position: "fixed", top: "50%", left: "50%",
      width: "100%", maxWidth: "90%",
      WebkitTransform: "translate(-50%,-50%)", msTransform: "translate(-50%,-50%)", transform: "translate(-50%,-50%)",
      zIndex: 999,
      transition: "opacity .5s ease-in-out",
      WebkitTransition: "opacity .5s ease-in-out",
      MsTransition: "opacity .5s ease-in-out",
      wordBreak: "break-word",
      textAlign: "center"
    });
    this.css(inner, {
      display: "inline-block",
      padding: ".8em 1em",
      borderRadius: ".3em",
      backgroundColor: "rgba(51,51,51,.8)", 
      color: "#fff", textAlign: "left"
    });
    container.appendChild( inner );
    document.body.appendChild( container );
    setTimeout( function(){ 
      self.css( container, { opacity: 0 } );
      setTimeout( function(){ document.body.removeChild( container ) }, 500);
    }, 2000 );
  };

  GH.prototype.delegate = function ( obj, target, type, callback ) {
    obj = ( typeof obj === "string" ? document.getElementById( obj ) : obj );
    obj.addEventListener( type, fun, false );
    function fun ( e ) {
      var t = e.target;
      while ( t ) {
        if ( t.nodeName.toLowerCase() === target.toLowerCase() ) {
          callback && callback.apply( t, [e] );
        }
        t = t.parentNode;
      }
    }
  };
  
  GH.prototype.toArray = function( data, level, path, result ) {
    for(var o in data) {
      var p = path + (level? "["+o+"]" : o);
      if (Object.prototype.toString.call(data[o]) === '[object Array]' || Object.prototype.toString.call(data[o]) === '[object Object]') {
        this.toArray(data[o],1 + level, p, result);
      } else {
          Object.prototype.toString.call(result) === '[object Object]' && (result[p] = data[o]);
          Object.prototype.toString.call(result) === '[object Array]' && result.push( p + "=" + data[o] );
        }
    };
    return result;
  };
  
  GH.prototype.ajax = function ( url, json, fnSucc, type ) {
    !!type || ( type = "post" );
    var data = this.toArray( json, 0, "", [] ).join("&"); // 数据操作
    
    var oAjax;
    oAjax = new XMLHttpRequest();// 创建ajax对象
    
    if ( type === "get" ) { // GET或者POST
      oAjax.open("GET", url + "?" + data + new Date().getTime(), true);
      oAjax.send();
    } else if (type === "post") {
      oAjax.open( "POST", url + "?" +new Date().getTime(), true);
      oAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      oAjax.send( data );
    };
    oAjax.onreadystatechange = function() {
      if( oAjax.readyState == 4 && oAjax.status == 200 ) {
        try {
          //返回的json字符串转换为对象
          fnSucc( JSON.parse(oAjax.responseText) );
        } catch(e) {
          fnSucc( oAjax.responseText );
        };
      }
    }
  };

  GH.prototype.serialize = function( form ) {
    form = (typeof form === "string") ? document.getElementById( form ) : form;

    var input = form.getElementsByTagName( "input" ),
        select = form.getElementsByTagName( "select" ),
        textarea = form.getElementsByTagName( "textarea" ),
        checkedBox = "",
        res = {}; //存放结果数据

    //遍历input类型  
    for(var i=0, inputSelf; inputSelf=input[i]; i++) {
      var inputType = inputSelf.getAttribute("type");
      switch ( inputType ) {
        case "checkbox":
          if ( inputSelf.checked ) { checkedBox += (inputSelf.value+",");}
          res[ inputSelf.getAttribute("name") ] = checkedBox;
        case "radio":
          if( inputSelf.checked ) { res[ inputSelf.getAttribute("name") ] = inputSelf.value; }
          break;
        case "submit":
          break;
        default:
          res[ inputSelf.getAttribute("name") ] = inputSelf.value;
          break;
      };
    };
    //遍历下拉列表
    for ( var i=0, selectSelf; selectSelf=select[i]; i++ ) {
      res[ selectSelf.getAttribute("name") ] = selectSelf.value;
    };
    //遍历多行文本框
    for ( var i=0, textareaSelf; textareaSelf=textarea[i]; i++ ) {
      res[ textareaSelf.getAttribute("name") ] = textareaSelf.value;
    };
    return res;
  };
  
  // 合并对象，返回obj1
  GH.prototype.extend = function( obj1, obj2 ) {
    !!obj1 || ( obj1 = {} );
    for (var i in obj1) {
      if ( obj2.hasOwnProperty(i) && !obj1.hasOwnProperty(i) ) {
        obj1[i] = obj2[i];
      };
    };
    return obj1;
  };
  
  // 判断浏览器内核
  GH.prototype.getUA = function() {
    var ua = window.navigator.userAgent,
        result = null,
        browsers = [
          "MSIE 8",
          "MSIE 9",
          "MSIE 10",
          "MSIE 11",
          "Firefox",
          "Opera",
          "Chrome",
          "iPhone",
          "Android",
          "Windows phone"
        ];
    for(var i = 0, item = null; item = browsers[i]; i++) {
      ( ua.indexOf( item ) >= 0 ) && ( result = item.replace("MSIE ", "ie") );
    };
    return result;
  };
  window.GH = new GH();
})( window );
